<template>
  <section>
    <div class="cont_box">
      <div class="cont_box_left">
        <el-form :inline="true" :model="formSearch" class="margin10">
          <el-form-item label="" v-if="$root.btnControl.find(item=>item=='role_bind_auth')">
            <el-button type="" @click="dialog = true">角色权限绑定</el-button>
          </el-form-item>
          <el-form-item label="" v-if="$root.btnControl.find(item=>item=='add')">
            <el-button type="primary" @click="changeHandle=1">添加</el-button>
          </el-form-item>
          <el-form-item label="" v-if="$root.btnControl.find(item=>item=='edit')">
            <el-button type="warning" @click="changeHandle=0">修改</el-button>
          </el-form-item>
          <el-form-item label="">
            <el-button type="info" @click="changeHandle = 1,getlist,formPush={}">重置</el-button>
          </el-form-item>
          <el-form-item label="">
            <!-- <el-button type="danger" @click="deleInfor">删除</el-button> -->
          </el-form-item>
        </el-form>
        <el-tree
          :data="formDataa"
          :props='defaultProps'
          :load="loadNode"
          lazy
          
          @node-click="treeClick"
          :filter-node-method="filterNode"
          :expand-on-click-node="false">
          <div class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <el-button v-if="!data.parentId&&data.parentId!=0&&$root.btnControl.find(item=>item=='delete')"
                       style="margin-left:30px;" type="danger" size="mini" @click="() => deleInfor(data)"> 删除
            </el-button>
          </div>
        </el-tree>
      </div>
      <div class="cont_box_right">
        <el-row>
          <el-form :inline="true" :model="formSearch" class="marginRight">
            <el-form-item :label="changeHandle == 1?'新增':'修改'" style="margin:0px;">
            </el-form-item>
          </el-form>
          <el-col :span="10">
            <el-form label-position="right" :rules="rules" label-width="80px" :model="formPush" ref='formPush'>
              <el-form-item label="所属组织" size="small" prop="orgId">
                <el-cascader
                  ref="cascader"
                  v-model="option1"
                  :options="dataTree"
                  :props="defaultProps2"
                  @change="handleChange"
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="formPush.name"></el-input>
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="formPush.description"></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="formPush.status">
                  <el-radio :label="true">启用</el-radio>
                  <el-radio :label="false">禁止</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button v-if="changeHandle == 1" size="medium " @click="addTree('formPush')">新增</el-button>
                <el-button v-else size="medium " type="warning" @click="upTree('formPush')">修改</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="14">
            <el-row class="sys_role_tree">
              <el-col :span="12">
                <span>菜单回显</span>
                <hr style="border-top: none; margin: 2px 0"/>
                <el-tree
                  :data="menuList1"
                  :props='defaultProps'
                  :default-expanded-keys="showmenuList1"
                  @check="handleCheckChange"
                  @node-click="treeClick11"
                  node-key="id"
                  ref="rightsTree1"
                >
                </el-tree>
              </el-col>
              <el-col :span="12" class="sys_role_table">
                <span>按钮权限回显</span>
                <hr style="border-top: none; margin: 2px 0"/>
                <div class="colorBlue">{{ btnFather1 }}</div>
                <el-table :data="formData111" :row-key="getkey" style="width: 100%" stripe
                          @selection-change="handleSelectionChange" ref="multipleTable">
                  <!-- <el-table-column type="selection" width="55" :reserve-selection="true" label="全选"></el-table-column> -->
                  <el-table-column prop="code" label="code"></el-table-column>
                  <el-table-column prop="name" label="名称"></el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 添加 -->
    <el-dialog title="菜单绑定" :visible.sync="dialog">
      <div class="cont_box_right">
        <el-form label-position="right" :rules="rules" label-width="90px" :model="formPush" ref='addList'>
          <el-form-item label="角色" size="small">
            <el-cascader
              ref="cascaderjs"
              v-model="option2"
              :options="formDataa"
              :props="defaultProps3"
              @change="handleChange1"
            >
            <!-- <template slot-scope="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="data.parentId?data.disabled = true:data.disabled = false"></span>
            </template> -->
            </el-cascader>
          </el-form-item>
          <el-form-item label="菜单" size="small">
            <el-row class="sys_role_tree">
              <el-col :span="12">
                <el-tree
                  :data="menuList"
                  :props='defaultProps'
                  :check-strictly="checkStrictly"
                  show-checkbox
                  :default-expanded-keys="showmenuList"
                  :default-checked-keys="showmenuList"
                  @check="handleCheckChange"
                  @node-click="treeClick1"
                  node-key="id"
                  ref="rightsTree"
                >
                </el-tree>
              </el-col>
              <el-col :span="12" class="sys_role_table">
                <div class="colorBlue">“{{ btnFather  }}”按钮权限</div>
                <el-table :data="formData11" :row-key="getkey" style="width: 100%" stripe
                          @select="handleSelectionChange" @select-all="handleSelectionChange" ref="multipleTable">
                  <el-table-column type="selection" width="55" label="全选"></el-table-column>
                  <el-table-column prop="code" label="code"></el-table-column>
                  <el-table-column prop="name" label="名称"></el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium " @click="dialog = false">取 消</el-button>
        <el-button size="medium " @click="binding()" :loading="dialoggg">绑 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {
  echoAuth,
  roleTreeBtn,
  menuList,
  bindmenuroleId,
  bindmenu,
  roletreeList,
  addroletreeList,
  updateroletreeList,
  deleteroletreeList,
  xqSelectList,
  orgTree,
  authority
} from '../../url/api';

export default {
  data() {
    return {
      option2: [],
      option1: [],
      checkStrictly: false,//控制树状图父级和子集的关联
      menuList: [],
      menuList1: [],
      showmenuList1: [],
      showmenuList: [],
      formDataa: [],
      dialog: false,
      dialoggg: false,
      changeHandle: 1,//1表示执行新增，0表示修改
      formSearch: {
        name: '',
        status: 1
      },//查询条件
      formPush: {},//表单提交
      defaultProps: {//树状图key定义
        children: 'children',
        label: 'name'
      },
      dataTree: [],//树数据
      formData: [],//树数据
      rules: {
        name: [{required: true, message: '该项不能为空'}],
        orgId: [{required: true, message: '该项不能为空', trigger: 'blur'}],
        status: [{required: true, message: '该项不能为空', trigger: 'change'}],
      },
      defaultProps2: {
        children: 'children',
        label: 'name',
        value: 'id',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      defaultProps3: {
        children: '',
        label: 'name',
        value: 'id',
        expandTrigger: 'hover',
        lazy: true,
        lazyLoad(node, resolve) {
          if (node.level === 0) {
            return resolve(node.data);
          }
          let data1 = node.data.data || []
          let data2 = node.data.children || []
          let data3 = [...data1, ...data2]
          resolve(data3);
        },
        checkStrictly: true
      },
      bindMenu: {
        id: '',
        menuIds: [],
        resources: [],
      },
      formData11: [],
      formData111: [],
      formData1: [],
      resources: [//只记录useAble为true的对象

      ],
      fatherCheckedObj: '',
      delTree: [],//删除树
      btnFather: '',
      btnFather1: '',
      deleBatch: [],//删除树
      currentTree: {},

    }
  },
  methods: {
    setMenuList(data) {
      this.menuList1 = data.filter(item => {
        if (item.children) {
          item.children = item.children.filter(item => {
            if (item.resources) {
              item.resources = item.resources.filter(item => item.useAble);
              return item.isEnable;
            }
          })
        }
        return item.isEnable;
      })
    },
    getkey(row) {
      return row.id
    },
    getRoleTreeBtn() {//查询角色拥有的菜单
      let params = {
        roleId: this.option2[this.option2.length - 1]
      }
      //console.log(params)
      roleTreeBtn(params).then(res => {
        //console.log(res)
        if (res.data.ok) {

        }
      })
    },
    treeClick1(data) {//树状图node节点点击事件,将该节点的数据填充，修改
      this.currentTree = data;
      this.btnFather = data.name
      this.formData11 = data.resources
      this.$nextTick(() => {
        data.resources.forEach(item => {
          item.parentId = data.parentId
          this.$refs.multipleTable.toggleRowSelection(item, item.useAble);
        })
      })
    },
    treeClick11(data) {//树状图node节点点击事件,将该节点的数据填充，修改
      this.btnFather1 = data.name
      this.formData111 = data.resources
      if (!data.isClicked) {
        data.resources.forEach(item => {
          item.parentId = data.parentId
          if (item.useAble) {
            this.$refs.multipleTable.toggleRowSelection(item);
          }
        })
      }
      // // this.$refs.multipleTable.clearSelection();
      data.isClicked = true
      // // this.getauthority(data)
      //console.log(data)
    },
    handleSelectionChange(val) {//列表多选//已经选中中左边的所有对象
      this.$refs.rightsTree1.setChecked(this.currentTree, val.length)
      let map = val.map(item => item.id);
      this.formData11.forEach(item => item.useAble = map.includes(item.id));
    },
    getauthority(data) {//查看用户菜单有权限资源列表

      if (!this.bindMenu.id) {
        this.$message("请先选择角色")
        return
      }
      let params = {
        menuId: data.id,
        bindMenuid: this.bindMenu.id,
      }
      authority(params).then(res => {
        //console.log(res)
        if (res.data.ok) {
          this.formData1 = res.data.data
          // //console.log(this.checkedObj,this.checkedObj.resources.length)
          this.formData1.forEach(item => {
            if (item.useAble) {
              this.$refs.multipleTable.toggleRowSelection(item);
            }
          })
        }
      })
    },
    getlist() {
      let params = sessionStorage.getItem('userId')
      roletreeList(params).then((res) => {//角色列表
        //console.log(res)
        if (res.data.ok) {
          this.formDataa = res.data.data
          console.log(this.formDataa,"QQQQQQQQQQQQQ");
        }
      })
    },
    loadNode(node, resolve) {
      if (node.level == 0) {
        return resolve(node.data);
      }
      let data1 = node.data.data || []
      let data2 = node.data.children || []
      let data3 = [...data1, ...data2]
      //console.log(data1,data2,data3)
      setTimeout(() => {
        const data = data3;
        resolve(data);
      }, 500);
    },
    getInit() {
      this.getlist()
      let org_tree = {
        name: '',
        status: 1
      }
      orgTree(org_tree).then((res) => {
        //console.log(res)
        if (res.data.ok) {
          this.dataTree = res.data.data
        }
      })
      this.checkStrictly = true
    },
    getmenuList() {
      //console.log(this.option2)
      let params = this.option2[this.option2.length - 1]
      this.formData11 = []
      this.$refs.multipleTable.clearSelection();
      if (params) {
        // echoAuth(params).then((res)=>{//角色列表
        //   //console.log(res)
        //   if(res.data.ok){
        //     this.menuList = res.data.data
        //   }
        // })
        this.menuList = []
        echoAuth(params).then((res) => {//查询系统所有的菜单
          //console.log(res)
          if (res.data.ok) {
            this.dialog = true
            this.menuList = res.data.data
            // this.getRoleTreeBtn()
            this.huixian()
          }
        })
        // this.menuList=[]
        // menuList(params).then((res)=>{//查询系统所有的菜单
        //   //console.log(res)
        //   if(res.data.ok){
        //     this.dialog = true
        //     this.menuList = res.data.data
        //     // this.getRoleTreeBtn()
        //     this.huixian()
        //   }
        // })
      }

    },
    getmenuList1() {
      //console.log(this.formPush.orgId)
      let params = this.formPush.id
      this.formData11 = []
      this.$refs.multipleTable.clearSelection();
      if (params) {
        this.menuList1 = []
        this.formData111 = [];
        menuList(params).then((res) => {//查询系统所有的菜单
          //console.log(res)
          if (res.data.ok) {
            // this.dialog = true
            this.setMenuList(res.data.data);
            this.huixian1()
          }
        })
      }

    },
    handleChange(value) {
      this.formPush.orgId = this.option1[this.option1.length - 1]
    },
    handleChange1(value) {//绑定角色
      console.log(this.formDataa,value);
      console.log(value, this.$refs['cascaderjs'].getCheckedNodes()[0].label)
      // console.log(formDataa);
      this.getmenuList()//左边列表
    },
    huixian() {
      this.checkStrictly = true
      this.bindMenu.id = this.option2[this.option2.length - 1]
      bindmenuroleId(this.bindMenu.id).then((res) => {//角色菜单回显
        //console.log(res)
        if (res.data.ok) {
          this.showmenuList = res.data.data

          this.$refs.rightsTree.setCheckedKeys(this.showmenuList);
          this.checkStrictly = false

          this.$nextTick(() => {
            setTimeout(() => {
              this.fatherCheckedObj = this.$refs.rightsTree.getCheckedNodes().filter(item => {
                item.isClicked = false//表示没有点击
                return item
              })
            }, 1000)
          });
          // this.showmenuList = res.data.data
          this.bindMenu.menuIds = this.showmenuList
        }
      })
    },
    huixian1() {
      this.checkStrictly = true
      this.bindMenu.id = this.formPush.id
      bindmenuroleId(this.bindMenu.id).then((res) => {//角色菜单回显
        //console.log(res)
        if (res.data.ok) {
          this.showmenuList1 = res.data.data
          this.checkStrictly = false

          // this.showmenuList = res.data.data
          this.bindMenu.menuIds = this.showmenuList
        }
      })
    },
    filterNode(value, data) {//树状图节点搜索
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    treeClick(data) {//树状图node节点点击事件,将该节点的数据填充，修改
      this.option1 = []
      this.changeHandle = 0;
      this.formPush = data
      this.option1 = [data.orgId]
      this.getmenuList1()
      //console.log(data)
    },
    addTree(formName) {//添加树状图node节点
      if (!this.formPush.orgId) {
        alert('请选择组织')
        return
      }
      let pramas = {
        name: this.formPush.name,
        orgId: this.formPush.orgId,
        status: this.formPush.status,
        description: this.formPush.description,
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          addroletreeList(pramas).then((res) => {
            //console.log(res)
            if (res.data.ok) {
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.getlist()
            }
          })
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },
    upTree(formName) {//修改树状图node节点
      if (!this.formPush.orgId) {
        alert('请选择组织')
        return
      }
      let pramas = {
        id: this.formPush.id,
        name: this.formPush.name,
        orgId: this.formPush.orgId,
        status: this.formPush.status,
        description: this.formPush.description,
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateroletreeList(pramas).then((res) => {
            //console.log(res)
            if (res.data.ok) {
              this.$message({
                message: '修改成功',
                type: 'warning'
              });
              this.getlist()
            }
          })
        } else {
          //console.log('error submit!!');
          return false;
        }
      });
    },
    deleInfor(data) {
      //console.log(data)
      let params = [data.id]
      this.$confirm('确认删除吗？')
        .then(_ => {
          deleteroletreeList(params).then((res) => {
            //console.log(res)
            if (res.data.ok) {
              this.$message('删除成功');
              this.getlist()
            }
          })
        })
        .catch(_ => {
        });

    },
    binding() {//角色绑定菜单
      this.dialoggg = true
      this.getCheckedData();
      //console.log(this.bindMenu)
      bindmenu(this.bindMenu).then((res) => {
        //console.log(res)
        if (res.data.ok) {
          this.$message({
            message: '绑定成功,重新登录后将更新权限',
            type: 'success'
          });
        }
        this.dialoggg = false
        this.dialog = false
      })
    },
    getCheckedData() {
      let checkedList = this.$refs.rightsTree.getCheckedNodes(false, true)
      const menuIds = [];
      const resourceIds = [];
      for (const checked of checkedList) {
        menuIds.push(checked.id);
        if (checked.resources) {
          for (const resource of checked.resources) {
            if (resource.useAble) {
              resourceIds.push(resource.id);
            }
          }
        }
      }
      this.bindMenu.menuIds = menuIds;
      this.bindMenu.resources = resourceIds;
    },
    handleCheckChange(checkedItem, obj) {//树状图选中
      const selected = obj.checkedKeys.includes(checkedItem.id);
      this.checkButton(checkedItem, selected, checkedItem.id);
      this.bindMenu.menuIds = this.$refs.rightsTree1.getCheckedKeys().concat(this.$refs.rightsTree1.getHalfCheckedKeys()) || []
    },
    checkButton(item, selected) {
      const children = item.children;
      if (children) {
        children.forEach(item => {
          this.checkButton(item, selected);
        })
      }
      const resources = item.resources;
      if (resources) {
        let current = item.id === this.currentTree.id;
        resources.forEach(item => {
          item.useAble = selected
          if (current) {
            this.$refs.multipleTable.toggleRowSelection(item, selected)
          }
        });
      }
    },
    getTreeArr(id, option) {//回显遍历组织id
      this.option1.unshift(id)
    }
  }
  ,
  mounted() {
    this.getInit()
  }
  ,
}
</script>
<style scoped>
.cont_box {
  width: 100%;
  display: flex;
}

.cont_box_left, .cont_box_right {
  flex: 1;
  background: transparent;
  padding: 10px;
}

.cont_box_left {
  margin-right: 10px;
}

.margin10 {
  margin-bottom: 10px;
}

.marginRight {
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.cont_box_right .el-form-item {
  margin-bottom: 20px;
}

.colorBlue {
  margin-left: 10px;
  color: #a1d6f4;
}
</style>
